package org.hk.kg.web.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hk.kg.utils.LocalResouce;
import org.hk.kg.web.BaseAction;
import org.hk.kg.web.HtmlRender;

public class CSSLinkRender implements HtmlRender {
	private static Log logger = LogFactory.getLog(CSSLinkRender.class);
	private static Pattern CSS_PATTERN = Pattern.compile("(type|href)[=]{1}[\"]([^\"]*)[\"]");
	private String valueHodler;
	public boolean validate(String line) {
		if(line.startsWith("<link"))
		{
			Matcher m = CSS_PATTERN.matcher(line);
			while(m.find())
			{
				String attr_name = m.group(1);
				valueHodler = m.group(2);
				
				if(attr_name.equalsIgnoreCase("href"))
				{
					return true;
				}
			}
		}
		return false;
	}

	public String execute(String line, BaseAction context) {
		InputStream ips = null;
		BufferedReader reader = null;
		StringBuffer bf = new StringBuffer("<style type=\"text/css\">");
		String newLine = null;
		try {
			ips = LocalResouce.getPageFile(valueHodler);
			reader = new BufferedReader(new InputStreamReader(ips));
			while((newLine = reader.readLine())!= null)
			{
				bf.append(newLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		bf.append("</style>");
		valueHodler = null;
		try {
			reader.close();
			ips.close();
		} catch (IOException e) {
			logger.error(e);
		}
		
		return bf.toString();
	}

}
